package pers.vic.third.tbk;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import pers.vic.base.craw.CrawlConnect;
import pers.vic.third.tbk.vo.SearchConponVo;
import pers.vic.third.tbk.vo.TaokeOrderVo;
import pers.vic.util.PropertiesUtil;
import pers.vic.util.RegexUtil;

/**
 * 淘宝客的调用第三方接口的工具类
 * {@link https://open.21ds.cn/index/index/openapi/id/1.shtml?ptype=1}
 * @author VIC
 *
 */
public class TbkThirdUtils {

	private static Logger logger = LoggerFactory.getLogger(TbkThirdUtils.class);
	
	
	//高佣金转链
	private static final String HIGH_CONVERT_URL =   "https://api.open.21ds.cn/apiv1/getitemgyurl";
	
	//无券商品转链.
	@Deprecated
	private static final String WUQUAN_CONVERT_URL =   "http://119.29.94.164/xiaocao/wuquan.action";
	
	//全网超级搜接口--所有淘客优惠券商品 喵有券
	private static final String SEARCH_COUPON_URL1 = "https://api.open.21ds.cn/apiv1/gettkmaterial";
	//全网超级搜接口--所有淘客优惠券商品 小草
	private static final String SEARCH_COUPON_URL = "http://119.29.94.164/xiaocao/search/coupon_item_list.action";
//	@Deprecated
//	private static final String ACCESS_TOKEN = "70002100448d0f18adb960e3f59d899c8694b92bbe2ad4f9ee92a0f5d2191bac40572ca3896913019";

	@Deprecated
	private static final String QQ = "1045268926";
	
	/**
	 * 喵有券APP_KEY
	 */
	private static final String  APP_KEY = PropertiesUtil.getStringByKey("myq.appkey");
	
	/**
	 * 喵有券thname
	 */
	private static final String tbname = PropertiesUtil.getStringByKey("myq.tbname");
	
	public static final String ACCESS_TOKEN_REDIS_KEY = "access_token_redis_key_006";

	/**
	 * 1. 高佣金转链
	 * {@link https://open.21ds.cn/index/index/openapi/id/1.shtml?ptype=1}
	 */
	public static String  highConvert(String itemId, String pid) {
		logger.info("高佣金转链itemId={}  pid={}  ", new Object[]{itemId, pid, });
		try {

			CrawlConnect c = con(HIGH_CONVERT_URL);
			c.data("apkey", APP_KEY).data("itemid", itemId)
					.data("shorturl","1")
					.data("pid", pid)
					.data("tbname", tbname);
			String text = c.getBodyText();
			logger.info("高佣金转链返回结果：{}", text);
			JSONObject object = JSON.parseObject(text);
			if(object != null) {
				JSONObject result = object.getJSONObject("result");
				if (result != null) {
					JSONObject data = result.getJSONObject("data");
					if (data != null) {                          
						/*String coupon_click_url = data.getString("coupon_click_url");
						if(StringUtils.isNotEmpty(coupon_click_url)){
							String coupon_info = data.getString("coupon_info");
							if(StringUtils.isNotBlank(coupon_info)) {
								return coupon_click_url;
							}else {
								String e  = RegexUtil.getFirstString(coupon_click_url, "\\?e=(.*?)&traceId=", 1);
								logger.info("e=\n{}",e);
								//return wuquanConver(e);
								return  data.getString("item_url");
							}
							
						}*/
						return data.getString("short_url");
						
					}
				}
			}
		} catch (Exception e) {
			logger.error("高佣金转链失败");
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;
	}
	@Deprecated
	public static String  highConvert(String itemId, Long adzoneId, Long siteId) {
		logger.info("高佣金转链itemId={}  adzoneId={} siteId={}", new Object[]{itemId, adzoneId, siteId});
		try {

			CrawlConnect c = con(HIGH_CONVERT_URL);
			c.data("token", getAccessToken()).data("item_id", itemId)
					.data("adzone_id", String.valueOf(adzoneId))
					.data("site_id", String.valueOf(siteId))
					.data("qq", QQ);
			String text = c.postBodyText();
			logger.info("高佣金转链返回结果：{}", text);
			JSONObject object = JSON.parseObject(text);
			if(object != null) {
				JSONObject result = object.getJSONObject("result");
				if (result != null) {
					JSONObject data = result.getJSONObject("data");
					if (data != null) {                          
						String coupon_click_url = data.getString("coupon_click_url");
						if(StringUtils.isNotEmpty(coupon_click_url)){
							String coupon_info = data.getString("coupon_info");
							if(StringUtils.isNotBlank(coupon_info)) {
								return coupon_click_url;
							}else {
								String e  = RegexUtil.getFirstString(coupon_click_url, "\\?e=(.*?)&traceId=", 1);
								return wuquanConver(e);
							}
						}
						
					}
				}
			}
		} catch (Exception e) {
			logger.error("高佣金转链失败");
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;
	}
	
	/**
	 * 2.无券商品转链.
	 * @param e 二合一链接
	 */
	@Deprecated
	public static String wuquanConver(String e){
		logger.info("无券商品转链 e= {}", e);
		try{
			CrawlConnect c = con(WUQUAN_CONVERT_URL);
			c.data("e", e)
			.data("appkey",APP_KEY)
			.data("qq", QQ);
			String text = c.postBodyText();
			logger.info("无券商品转链.：{}", text);
			JSONObject object = JSON.parseObject(text);
			if(object != null) {
				String clickUrl = object.getJSONObject("iteminfo").getJSONObject("data").getJSONObject("result").getJSONObject("item").getString("clickUrl");
				//String clickUrl = object.getString("clickUrl");
				if(!StringUtils.isEmpty(clickUrl)){
					return "https:" + clickUrl;
				}
			}
		}catch(Exception ex){
			logger.error("无券商品转链失败");
			logger.error(ExceptionUtils.getStackTrace(ex));
		}
		
		return null;
		
	}
	
	

	protected static CrawlConnect con(String url) {
		Connection conn = Jsoup.connect(url).ignoreContentType(true).timeout(5000);
		return new CrawlConnect(conn);
	}
	
	public static void  test() throws IOException{
		String url = "http://item.taobao.com/item.htm?id=542445155652";
		CrawlConnect c = con(url);
		String text = c.getHtml();
		logger.info(text);
	}
	/**
	 * 全网超级搜接口--所有淘客优惠券商品 喵有券
	 * @param keyword
	 * @return
	 */
	
	private static final String adzoneid = "732090191";
	
	private static final String siteid = "45558477";
	public static List<SearchConponVo> searchCoupon1(String keyword, int pageNum){
		try{
			CrawlConnect c = con(SEARCH_COUPON_URL1);
			c.data("keyword",keyword)
			.data("apkey",APP_KEY)
			//Pid第三段
			.data("adzoneid",adzoneid)
			//Pid第三段
			.data("siteid",siteid)
			.data("tbname",tbname);
			String text = c.getBodyText();
			
			JSONObject result = JSONObject.parseObject(text);
			logger.info("全网超级搜接口--所有淘客优惠券商品结果：{}", text);
			
			if(result != null) {
				JSONArray  data = result.getJSONArray("data");
				logger.info("{}",data);
				if(data != null) {
					String js = JSONObject.toJSONString(data);
					List<SearchConponVo> list = JSONObject.parseArray( js, SearchConponVo.class);
					return list;
				}
			}
		}catch(Exception e) {
			logger.error("全网超级搜接口--所有淘客优惠券商品出错");
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;
		
	}
	
	private static final String pid = "mm_132345716_45558477_732090191";
	@Deprecated
	public static List<SearchConponVo> searchCoupon(String q, int pageNum){
		try{
			CrawlConnect c = con(SEARCH_COUPON_URL);
			c.data("q",q).data("pageNum",String.valueOf(pageNum)).data("pid",pid).data("qq",QQ);
			String text = c.getBodyText();
			
			JSONObject result = JSONObject.parseObject(text);
			logger.info("全网超级搜接口--所有淘客优惠券商品结果：{}", text);
			
			if(result != null) {
				JSONObject success = result.getJSONObject("success");
				if(success != null) {
					JSONArray  data = success.getJSONArray("data");
					if(data != null) {
						String js = JSONObject.toJSONString(data);
						List<SearchConponVo> list = JSONObject.parseArray( js, SearchConponVo.class);
						return list;
					}
				}
			}
		}catch(Exception e) {
			logger.error("全网超级搜接口--所有淘客优惠券商品出错");
			logger.error(ExceptionUtils.getStackTrace(e));
		}
		return null;
		
	}
	
	private static final String ORDER_URL = "https://api.open.21ds.cn/apiv1/gettkorder";
	/**
	 * 通过喵有券获取订单
	 * {@link https://open.21ds.cn/index/index/openapi/id/4.shtml?ptype=1}
	 * @param starttime 订单查询开始时间（*必要，并且日期需进行URLENCODE编码） URLENCODE('2018-05-23 12:18:22')
	 * @param span 订单查询时间范围,单位:秒,最小60,最大1200（*必要），仅当查询常规订单，及三方订单时需要设置此参数，渠道，及会员订单不需要设置此参数，直接通过设置page_size,page_no 翻页查询数据即可
	 * @param page 第几页，默认1，1~100 （必填）
	 * @param pagesize 每页数据多少条，1~100 （必填）
	 * @param tkstatus  订单状态，1: 全部订单，3：订单结算，12：订单付款， 13：订单失效，14：订单成功； 订单查询类型为‘结算时间’时，只能查订单结算状态 （必填）
	 * @param orderscene  订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1，
	 * @param ordercounttype 订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
	 * @param ordertype 订单查询类型，创建时间“create_time”，或结算时间“settle_time” （必填）
	 * @throws UnsupportedEncodingException 
	 */
	public static List<TaokeOrderVo> findOrders(String starttime, Integer span, Integer page, Integer pagesize, Integer tkstatus) throws Exception {
		logger.info("开始请求淘宝订单数据,开始时间:{},时间范围:{}秒，页码:{},数据量:{},订单状态:{}", new Object[] {
				starttime, span, page, pagesize, tkstatus
		});
		starttime = URLEncoder.encode(starttime, "UTF-8");
		CrawlConnect c = con(ORDER_URL);
		c.data("apkey", APP_KEY)
			.data("tbname", tbname)
			.data("ordertype", "create_time")
			.data("starttime", starttime)
			.data("span", String.valueOf(span))
			.data("page", String.valueOf(page))
			.data("pagesize", String.valueOf(pagesize))
			.data("tkstatus", String.valueOf(tkstatus));
		String text = c.getBodyText();
		JSONObject object = JSONObject.parseObject(text);
		if(object == null) {
			return null;
		}
		if(object.getInteger("code") != 200) {
			logger.info("未获取到订单数据,msg={}", object.getString("msg"));
		}
		JSONObject data = object.getJSONObject("data");
		if(data != null) {
			if(text.contains("[")) {//说明返回的是个数组
				JSONArray arr = data.getJSONArray("n_tbk_order");
				List<TaokeOrderVo> list = JSON.parseArray(arr.toJSONString(), TaokeOrderVo.class);
				logger.info("订单数据采集到{}条数据", list.size());
				return list;
			}else {
				JSONObject obj = data.getJSONObject("n_tbk_order");
				TaokeOrderVo vo =JSON.parseObject(obj.toJSONString(), TaokeOrderVo.class);
				logger.info("订单数据采集到1条数据");
				return new ArrayList<TaokeOrderVo>(Arrays.asList(vo)) ;
				
			}
		}
		
		return null;
	}
	
	
	public static String getAccessToken(){
		return "70002100b14544994e687d9e9c19ca79bc1ea864a1362e09ab2bab6b46cd07b20d228743896913019";
	}
	
	
	
	public static void main(String[] args) throws Exception {
//		String itemId = "564906644821";
//		Long adzoneId1 = 44110950192L;
//		Long adzoneId =  44135550022L;
//		Long siteId = 46060202L;
//		String pid = "mm_132345716_46060202_44781700335";
//		System.out.println(highConvert(itemId, pid));
		
		//searchCoupon("零食",2);
//		String s = URLEncoder.encode("2018-12-12 05:05:06", "UTF-8");
//		System.out.println(s);
		test3();
	}
	
	private static String startTime = "2018-10-18 04:30:00";
	public static void test3() throws Exception {
		
		List<TaokeOrderVo> list = findOrders(startTime, 1200, 1, 100, 1);
		if(list== null) return;
		for(TaokeOrderVo v : list) {
			System.out.println(v);
		}
		
	}
	
	public static void test2() {
		String s1 = "{\"code\":200,\"data\":{\"n_tbk_order\":{\"adzone_id\":\"xxxxxx\",\"adzone_name\":\"xxxxxx\",\"alipay_total_price\":\"9.9000\",\"auction_category\":\"餐饮具\",\"commission\":\"0.00\",\"commission_rate\":\"1.0000\",\"create_time\":\"2018-12-12 15:15:20\",\"income_rate\":\"xxxxxxx\",\"item_num\":\"1\",\"item_title\":\"xxxxxxx\",\"num_iid\":\"573726813447\",\"order_type\":\"天猫\",\"pay_price\":\"0.00\",\"price\":\"138.00\",\"pub_share_pre_fee\":\"0.55\",\"seller_nick\":\"xxxxxxxxx\",\"seller_shop_title\":\"xxxxxxx\",\"site_id\":\"xxxxxxx\",\"site_name\":\"xxxxxx\",\"subsidy_fee\":\"0\",\"subsidy_rate\":\"0.0050\",\"subsidy_type\":\"1\",\"terminal_type\":\"2\",\"total_commission_fee\":\"0\",\"total_commission_rate\":\"0.0500\",\"trade_id\":\"xxxxxxxx\",\"trade_parent_id\":\"xxxxxxxxx\"}},\"msg\":\"获取成功\"}";
		
		String s2 = "{\"code\":200,\"data\":{\"n_tbk_order\":[{\"adzone_id\":\"xxxxx\",\"adzone_name\":\"拉新活动\",\"alipay_total_price\":\"64.0000\",\"auction_category\":\"个人护理/保健\",\"commission\":\"0.00\",\"commission_rate\":\"1.0000\",\"create_time\":\"2018-12-12 15:15:20\",\"income_rate\":\"xxxxxxx\",\"item_num\":\"1\",\"item_title\":\"xxxxxxx\",\"num_iid\":\"xxxxxx\",\"order_type\":\"天猫\",\"pay_price\":\"0.00\",\"price\":\"259.00\",\"pub_share_pre_fee\":\"12.80\",\"seller_nick\":\"xxxx旗舰店\",\"seller_shop_title\":\"xxxx旗舰店\",\"site_id\":\"xxxxx\",\"site_name\":\"xxxxxx\",\"subsidy_fee\":\"0\",\"subsidy_rate\":\"0.0000\",\"subsidy_type\":\"-1\",\"terminal_type\":\"2\",\"tk_status\":\"12\",\"total_commission_fee\":\"0\",\"total_commission_rate\":\"0.2000\",\"trade_id\":\"xxxxxxxx\",\"trade_parent_id\":\"xxxxxxxx\"},{\"adzone_id\":\"xxxxxxx\",\"adzone_name\":\"小xxxxx\",\"alipay_total_price\":\"129.0000\",\"auction_category\":\"厨房电器\",\"commission\":\"0.00\",\"commission_rate\":\"1.0000\",\"create_time\":\"2018-12-10 15:12:14\",\"income_rate\":\"0.0180\",\"item_num\":\"1\",\"item_title\":\"xxxxxxxx\",\"num_iid\":\"xxxxxxx\",\"order_type\":\"天猫\",\"pay_price\":\"0.00\",\"price\":\"299.00\",\"pub_share_pre_fee\":\"2.33\",\"seller_nick\":\"xxxxxx专卖店\",\"seller_shop_title\":\"xxxxxxx专卖店\",\"site_id\":\"xxxxxx\",\"site_name\":\"xxxxxx\",\"subsidy_fee\":\"0\",\"subsidy_rate\":\"0.0030\",\"subsidy_type\":\"1\",\"terminal_type\":\"2\",\"tk_status\":\"12\",\"total_commission_fee\":\"0\",\"total_commission_rate\":\"0.0150\",\"trade_id\":\"xxxxxx\",\"trade_parent_id\":\"xxxxxxx\"}]},\"msg\":\"获取成功\"}";
		
		JSONObject j1 = JSONObject.parseObject(s1);
		JSONObject j2 = JSONObject.parseObject(s2);
		JSONObject a1 = j1.getJSONObject("data").getJSONObject("n_tbk_order");
		JSONArray a2 = j2.getJSONObject("data").getJSONArray("n_tbk_order");
		TaokeOrderVo vo =JSON.parseObject(a1.toJSONString(), TaokeOrderVo.class);
		System.out.println(vo.getCreate_time());
		System.out.println(vo.toString());
		List<TaokeOrderVo> list = JSON.parseArray(a2.toJSONString(), TaokeOrderVo.class);
		for(TaokeOrderVo v : list)
			System.out.println(v);
		
	}


}
